package system

import (
	"encoding/json"
	"ltbz/cultural_tourism_api/controllers"
	"ltbz/cultural_tourism_api/models"
	"ltbz/cultural_tourism_api/models/system"
	"ltbz/cultural_tourism_api/utils"
	"time"

	systemServices "ltbz/cultural_tourism_api/services/system"
)

// 系统管理
type SysDeptController struct {
	controllers.BaseAuthController
}

// @Tags 系统部门管理
// @Title 部门列表
// @Description 部门列表
// @Param	request	body system.DeptListReq true "type json string"
// @Success 200
// @router /dept/list [post]
func (this *SysDeptController) List() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	body := this.Ctx.Input.RequestBody
	req := new(system.DeptListReq)
	if string(body) != "" {
		err := json.Unmarshal(body, &req)
		if err != nil {
			br.Msg = "参数解析异常！"
			br.ErrMsg = "参数解析失败，Err:" + err.Error()
			return
		}
	}
	if req.PageSize <= 0 {
		req.PageSize = utils.PageSize20
	}
	if req.CurrentIndex <= 0 {
		req.CurrentIndex = 1
	}

	startSize := utils.StartIndex(req.CurrentIndex, req.PageSize)

	count, list, err, _ := systemServices.DeptTreeList(req, startSize, req.PageSize)
	if err != nil {
		br.Msg = "获取失败！"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	resp := new(system.SysDeptListPageResp)
	page := utils.GetPaging(req.CurrentIndex, req.PageSize, count)
	resp.Paging = page
	resp.List = list

	br.Msg = "获取成功"
	br.Ret = 200
	br.Data = resp
}

// @Tags 系统部门管理
// @Title 新增部门
// @Description 新增部门
// @Param	request	body system.SysDeptAddReq true "type json string"
// @Success 200
// @router /dept/add [post]
func (this *SysDeptController) Add() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req system.SysDeptAddReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	item := new(system.SysDept)
	item.ParentId = req.ParentId
	item.DeptName = req.DeptName
	item.Sort = req.Sort
	if req.ParentId > 0 {
		parentInfo, tErr := item.GetDeptByDeptId(req.ParentId)
		if tErr != nil {
			if tErr.Error() == utils.ErrNoRow() {
				br.Msg = "上级部门不存在！"
				br.ErrMsg = "上级部门不存在"
				return
			}
			br.Msg = "查询上级部门出错！"
			br.ErrMsg = "查询上级部门出错,Err:" + err.Error()
			return
		}
		if parentInfo.RootId == 0 {
			item.RootId = parentInfo.DeptId
		} else {
			item.RootId = parentInfo.RootId
		}

		item.Level = parentInfo.Level + 1
	}
	// 判断是否存在相同的部门名称
	cond := " AND parent_id = ? AND dept_name = ?"
	pars := make([]interface{}, 0)
	pars = append(pars, item.ParentId, item.DeptName)
	exitList, err := item.GetDeptListByCondition(cond, pars, "")
	if err != nil {
		br.Msg = "查询部门出错！"
		br.ErrMsg = "查询部门出错,Err:" + err.Error()
		return
	}
	if len(exitList) > 0 {
		br.Msg = "该部门名称已存在！"
		br.ErrMsg = "该部门名称已存在"
		return
	}
	item.CreateTime = time.Now()
	item.ModifyTime = time.Now()
	err = item.Add()
	if err != nil {
		br.Msg = "保存失败！"
		br.ErrMsg = "保存失败,Err:" + err.Error()
		return
	}
	br.Msg = "保存成功"
	br.Ret = 200
	//处理父级对应的所有子级
	if req.ParentId != 0 {
		err = item.HandleDeptChildId(req.ParentId)
		if err != nil {
			br.Msg = "处理子级失败！"
			br.ErrMsg = "处理子级失败,Err:" + err.Error()
			return
		}
	}
	return
}

// @Tags 系统部门管理
// @Title 编辑部门
// @Description 编辑部门
// @Param	request	body system.SysDeptEditReq true "type json string"
// @Success 200
// @router /dept/edit [post]
func (this *SysDeptController) Edit() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req system.SysDeptEditReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	item := new(system.SysDept)
	item.DeptId = req.DeptId
	item.ParentId = req.ParentId
	item.DeptName = req.DeptName
	item.Sort = req.Sort

	//查询当前部门是否已存在
	deptInfo, err := item.GetDeptByDeptId(req.DeptId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "该部门不存在！"
			br.ErrMsg = "该部门不存在，Err:" + err.Error()
			return
		}
		br.Msg = "查询部门出错！"
		br.ErrMsg = "查询部门出错，Err:" + err.Error()
		return
	}
	updateParams := make(map[string]interface{})
	whereParam := make(map[string]interface{})

	if deptInfo.ParentId > 0 && deptInfo.ParentId != item.ParentId {
		parentInfo, tErr := item.GetDeptByDeptId(req.ParentId)
		if tErr != nil {
			if err.Error() == utils.ErrNoRow() {
				br.Msg = "上级部门不存在！"
				br.ErrMsg = "上级部门不存在，Err:" + err.Error()
				return
			}
			br.Msg = "查询上级部门出错！"
			br.ErrMsg = "查询上级部门出错，Err:" + err.Error()
			return
		}
		if parentInfo.RootId == 0 {
			item.RootId = parentInfo.DeptId
		} else {
			item.RootId = parentInfo.RootId
		}
		item.Level = parentInfo.Level + 1
		updateParams["parent_id"] = item.ParentId
		updateParams["root_id"] = item.RootId
		updateParams["level"] = item.Level
	} else if req.ParentId == 0 && deptInfo.ParentId != item.ParentId {
		item.RootId = 0
		item.Level = 0
		updateParams["parent_id"] = item.ParentId
		updateParams["root_id"] = item.RootId
		updateParams["level"] = item.Level
	}
	if deptInfo.Sort != item.Sort {
		updateParams["sort"] = item.Sort
	}

	if deptInfo.DeptName != item.DeptName {
		cond := " AND parent_id = ? AND dept_name = ?"
		pars := make([]interface{}, 0)
		pars = append(pars, item.ParentId, item.DeptName)
		exitList, err := item.GetDeptListByCondition(cond, pars, "")
		if err != nil {
			br.Msg = "查询部门出错！"
			br.ErrMsg = "查询部门出错，Err:" + err.Error()
			return
		}
		if len(exitList) > 0 {
			br.Msg = "该部门名称已存在！"
			br.ErrMsg = "该部门名称已存在"
			return
		}
		updateParams["dept_name"] = item.DeptName
	}
	updateParams["modify_time"] = time.Now()
	whereParam["dept_id"] = req.DeptId
	err = item.Update(updateParams, whereParam)
	if err != nil {
		br.Msg = "保存失败！"
		br.ErrMsg = "保存失败,Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Msg = "保存成功"
	//处理父级对应的所有子级
	err = item.HandleDeptChildId(req.DeptId)
	if err != nil {
		br.Msg = "处理子级失败！"
		br.ErrMsg = "处理子级失败,Err:" + err.Error()
		return
	}
	return
}

// @Tags 系统部门管理
// @Title 删除部门
// @Description 删除部门
// @Param	request	body system.DelSysDeptReq true "type json string"
// @Success 200
// @router /dept/delete [post]
func (this *SysDeptController) Delete() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req system.DelSysDeptReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.DeptId <= 0 {
		br.Msg = "参数错误！"
		br.ErrMsg = "参数错误，Err:" + err.Error()
		return
	}
	item := new(system.SysDept)
	deptDetail, err := item.GetDeptByDeptId(req.DeptId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "部门已被删除，请刷新列表页面！"
			br.ErrMsg = "部门已被删除，请刷新列表页面！，Err:" + err.Error()
			return
		} else {
			br.Msg = "获取部门详情失败！"
			br.ErrMsg = "获取部门详情失败！，Err:" + err.Error()
			return
		}
	}
	err, errMsg := systemServices.DeleteDept(&req)
	if err != nil {
		br.Msg = "删除失败！"
		br.ErrMsg = "删除失败，Err:" + err.Error() + ";errMsg:" + errMsg
		return
	}
	br.Msg = "删除成功"

	//处理父级对应的所有子级
	err = item.HandleDeptChildId(deptDetail.ParentId)
	if err != nil {
		br.Msg = "处理子级失败！"
		br.ErrMsg = "处理子级失败,Err:" + err.Error()
		return
	}
	br.Ret = 200
}

// @Tags 系统部门管理
// @Title 部门列表
// @Description 部门列表
// @Param	request	body system.DelSysDeptReq true "type json string"
// @Success 200
// @router /dept/admin [post]
func (this *SysDeptController) AdminList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	list, err, errMsg := systemServices.DeptAdminTreeList()
	if err != nil {
		br.Msg = "获取失败！"
		br.ErrMsg = "获取失败，Err:" + err.Error() + ";errMsg:" + errMsg
		return
	}
	br.Msg = "获取成功"
	br.Ret = 200
	br.Data = list
}

// @Tags 系统部门管理
// @Title 部门列表
// @Description 部门列表
// @Param	request	body system.DeptAllReq true "type json string"
// @Success 200
// @router /dept/all [post]
func (this *SysDeptController) All() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	body := this.Ctx.Input.RequestBody
	req := new(system.DeptAllReq)
	if string(body) != "" {
		err := json.Unmarshal(body, &req)
		if err != nil {
			br.Msg = "参数解析异常！"
			br.ErrMsg = "参数解析失败，Err:" + err.Error()
			return
		}
	}

	list, err, _ := systemServices.DeptTreeAll(req)
	if err != nil {
		br.Msg = "获取失败！"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	br.Msg = "获取成功"
	br.Ret = 200
	br.Data = list
}
